package com.zyf.service.img;

import com.zyf.utils.ImageUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理图片合成操作类
 */
public class HandleImageMergeService {
    /**
     * 将单个文本合并到图片中
     */
    public String mergeSingleText2Image(String txtPath) throws Exception {
        //读取源文件
        String outpath = "";
        List<String> txtlist = getSrcTxt(txtPath);
        int srctotaline = txtlist.size();
        List<String> srclist = new ArrayList<>();
        if (srctotaline > 30) {//行数大于30,则进行单行4列组合
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < srctotaline; i++) {
                String line = txtlist.get(i);
                if (i == 0 || i == 1) {
                    srclist.add(line);
                    continue;
                }
                if (i % 2 == 0) {
                    if (buffer.length() > 0) {
                        srclist.add(buffer.toString());
                        buffer.delete(0, buffer.length());
                    }
                    buffer.append(line);
                } else {
                    buffer.append(line);
                }
            }
        } else {
            srclist = txtlist;
        }
        InputStream inputstream = null;
        int imgHerght = 0;
        int imgWidth = 0;
        BufferedImage bimage = null;
        try {
            //图片加载到缓冲区
            inputstream = this.getClass().getClassLoader().getResourceAsStream("tag_s1300.jpg");
            bimage = ImageIO.read(inputstream);
            //图片的高
            imgHerght = bimage.getHeight();
            //图片的宽
            imgWidth = bimage.getWidth();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            inputstream.close();
        }
        //计算字体大小
        int totaline = srclist.size();
        String fontsizeStr = imgHerght / (totaline * 1.6) + "";//减去间隔10*totalline-1,同时减去上下一个字的空隙
        int fontsize;
        if (fontsizeStr.contains(".")) {
            fontsize = Integer.valueOf(fontsizeStr.substring(0, fontsizeStr.indexOf(".")));
        } else {
            fontsize = Integer.valueOf(fontsizeStr);
        }
        //确定具体的字体大小
        if (fontsize >= 100) {
            fontsize = 100;
        } else if (fontsize >= 95) {
            fontsize = 95;
        } else if (fontsize >= 90) {
            fontsize = 90;
        } else if (fontsize >= 85) {
            fontsize = 85;
        } else if (fontsize >= 80) {
            fontsize = 80;
        } else if (fontsize >= 75) {
            fontsize = 75;
        } else if (fontsize >= 70) {
            fontsize = 70;
        } else if (fontsize >= 65) {
            fontsize = 65;
        } else if (fontsize >= 60) {
            fontsize = 60;
        } else if (fontsize >= 55) {
            fontsize = 55;
        } else if (fontsize >= 50) {
            fontsize = 50;
        } else if (fontsize >= 45) {
            fontsize = 45;
        } else if (fontsize >= 40) {
            fontsize = 40;
        } else if (fontsize >= 35) {
            fontsize = 35;
        } else if (fontsize >= 30) {
            fontsize = 30;
        } else if (fontsize >= 25) {
            fontsize = 25;
        } else if (fontsize >= 20) {
            fontsize = 20;
        } else if (fontsize >= 10) {
            fontsize = 13;
        }
        String intervalStr = fontsize * 0.9 + "";
        int interval;
        if (intervalStr.contains(".")) {
            interval = Integer.valueOf(intervalStr.substring(0, intervalStr.indexOf(".")));
        } else {
            interval = Integer.valueOf(intervalStr);
        }
        System.out.println("开始添加文字----");
        try {
            outpath = txtPath.replace(".txt", ".png");
            File file = new File(outpath);
            if (!file.exists()) {
                file.createNewFile();
            }
            for (String temp : srclist) {
                int maxtxtWidth = (temp.length() + 2) * fontsize;//留出两个字的边缘位置
                if (maxtxtWidth >= imgWidth) {
                    fontsize = imgWidth / (temp.length() + 2);
                    break;
                }
            }
            //确定文字的起始位置
            int initTxtY = (imgHerght - totaline * fontsize - (totaline-1) * interval) / 2;
            Font font = new Font("楷体", Font.BOLD, fontsize);   //定义字体  楷体
            Color color = new Color(6, 3, 3, 241);
            for (String temp : srclist) {
                int res = ImageUtils.drawTextToImgByDefault(bimage, temp.trim(), outpath, font, initTxtY, color, imgWidth, fontsize);
                initTxtY += fontsize + interval;//10个的间隔
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("------添加文字结束");
        return outpath;
    }

    /**
     * 读取源文件
     */
    private List<String> getSrcTxt(String filepath) throws FileNotFoundException {
        List<String> srcTxtlist = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (temp.length() > 0) {
                    srcTxtlist.add(temp);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return srcTxtlist;
    }


    /**
     * 生成封面图片
     *
     * @return
     */
    public String createCoverImgByContent(List<String> srclist, String imgpath, int fontsize) throws Exception {
        InputStream inputstream = null;
        int imgHerght = 0;
        int imgWidth = 0;
        BufferedImage bimage = null;
        try {
            //图片加载到缓冲区
            inputstream = this.getClass().getClassLoader().getResourceAsStream("tag_s1300.jpg");
            bimage = ImageIO.read(inputstream);
            //图片的高
            imgHerght = bimage.getHeight();
            //图片的宽
            imgWidth = bimage.getWidth();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            inputstream.close();
        }
        int initTxtY = (imgHerght - 3 * fontsize) / 2 - 50;
        String outpath = "";
        try {
            File imgFile = new File(imgpath);
            outpath = imgFile.getParent() + File.separator + "cover.png";
            File file = new File(outpath);
            if (!file.exists()) {
                file.createNewFile();
            }
            Font font = new Font("楷体", Font.BOLD, fontsize);   //定义字体
            Color color = new Color(6, 3, 3, 241);
            for (int i = 0; i < srclist.size(); i++) {
                String temp = srclist.get(i);
                if (i < srclist.size() - 1) {
                    int res = ImageUtils.drawTextToImgByDefault(bimage, temp.trim(), outpath, font, initTxtY, color, imgWidth, fontsize);
                    initTxtY += fontsize + 10;//10个的间隔
                } else {
                    Font lastfont = new Font("楷体", Font.BOLD, fontsize - 80);   //定义字体
                    int res = ImageUtils.drawTextToImgByDefault(bimage, temp.trim(), outpath, lastfont, initTxtY, color, imgWidth, fontsize - 80);
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return outpath;
    }

    /**
     * 生成封面图片
     *
     * @return
     */
    public String createCoverImgByContentByWidth(List<String> srclist, String imgpath, int imgWidth,int imgHeight, int fontsize) throws Exception {
        InputStream inputstream = null;
        BufferedImage bimage = null;
        try {
            //图片加载到缓冲区
            inputstream = this.getClass().getClassLoader().getResourceAsStream("tag_s1300.jpg");
            bimage = ImageIO.read(inputstream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            inputstream.close();
        }
        int initTxtY = (imgHeight - (srclist.size()-1) * fontsize) / 2 ;
        String outpath = "";
        try {
            File imgFile = new File(imgpath);
            outpath = imgFile.getParent() + File.separator + "cover.png";
            File file = new File(outpath);
            if (!file.exists()) {
                file.createNewFile();
            }
            Font font = new Font("楷体", Font.BOLD, fontsize);   //定义字体
            Color color = new Color(6, 3, 3, 241);
            for (int i = 0; i < srclist.size(); i++) {
                String temp = srclist.get(i);
                if (i < srclist.size() - 1) {
                    int res = ImageUtils.drawTextToImgByDefault(bimage, temp.trim(), outpath, font, initTxtY, color, imgWidth, fontsize);
                    initTxtY += fontsize + 10;//10个的间隔
                } else {
                    Font lastfont = new Font("楷体", Font.BOLD, fontsize - 80);   //定义字体
                    int res = ImageUtils.drawTextToImgByDefault(bimage, temp.trim(), outpath, lastfont, initTxtY, color, imgWidth, fontsize - 80);
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return outpath;
    }

    /**
     * 根据传入文件生成封面图片
     *
     * @return
     */
    public String createCoverImg(String txtpath, String imagepath, int fontsize) throws Exception {
        List<String> content = getSrcTxt(txtpath);
        String finalpath = createCoverImgByContent(content, imagepath, fontsize);
        return finalpath;
    }














}
